package cn.yuysaln.domain.activity.service.armory;

import cn.yuysaln.domain.activity.model.entity.ActivitySkuEntity;
import cn.yuysaln.domain.activity.repository.IActivityRepository;
import cn.yuysaln.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ActivityArmory implements IActivityArmory,IActivityDispatch{

    @Resource
    private IActivityRepository activityRepository;


    @Override
    public boolean assembleActivitySku(Long sku) {
        ActivitySkuEntity skuEntity = activityRepository.queryActivitySku(sku);
        //以sku---stockCount 形式缓存进行预热
        cacheActivitySkuStockCount(sku,skuEntity.getStockCount());
        //预热活动以及活动次数（查询已经做了缓存）
        activityRepository.queryRaffleActivityByActivityId(skuEntity.getActivityId());
        activityRepository.queryRaffleActivityCountByActivityCountId(skuEntity.getActivityCountId());

        return false;
    }

    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        //每个sku绑定了活动ID，通过该ID查询所有该活动下的sku实体
        List<ActivitySkuEntity> activitySkuEntities = activityRepository.queryActivitySkuListByActivityId(activityId);
        for (ActivitySkuEntity activitySkuEntity : activitySkuEntities) {
            //以sku---stockCount 形式缓存进行预热
            cacheActivitySkuStockCount(activitySkuEntity.getSku(),activitySkuEntity.getStockCount());
            //缓存每个sku的活动规定参与次数
            activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }
        //缓存当前活动
        activityRepository.queryRaffleActivityByActivityId(activityId);
        return true;
    }

    private void cacheActivitySkuStockCount(Long sku, Integer stockCount) {
        String key =  Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY+sku;
        activityRepository.cacheActivitySkuStockCount(key,stockCount);
    }
    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String  key = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY+sku;
        return activityRepository.subtractionActivitySkuStock(sku,key,endDateTime);
    }
}
